package com.oceansoft.mobile.weixin.util;

import com.oceansoft.mobile.biz.api.entity.Member;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.util.CacheBaseService;
import com.oceansoft.mobile.common.util.CommonUtilCache;
import com.oceansoft.mobile.common.util.HttpClientUtil;
import com.oceansoft.mobile.common.util.Result;
import com.oceansoft.mobile.weixin.entity.*;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.util.StringUtils;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.io.*;
import java.net.ConnectException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class WeixinUtil {
	//这里使用的是固定的一个通过认证的服务号的appid和secret，目的是让订阅号也能通过网页授权
	public static String APPID="wxe8dc58e12b05f6a7";
	public static String SECRET="1df11da8734cf02dbb79989f27021d7c";
	public static String WXOPENID="gh_b6af115f3e1a";

	//这里使用的是固定的一个通过认证的服务号的appid和secret，目的是从获取省厅的access_token
	public static String STAPPID="10000149";
	public static String STAPPKEY="083b80307ddb93da0069391be36802e5";
	/**
	 * 获取access_token接口(通用接口)
	 */
	public static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	public static String GETTICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";

	/**
	 * 获取省厅的access_token接口（2个小时过期）
	 */
	public static String ST_ACCESS_TOKEN_URL="http://www.api.jsga.gov.cn/api/api/get_access_token?app_id=STAPPID&app_key=STAPPKEY";

	/**
	 * 	省厅公众号授权接口
	 */
	public static String ST_GET_STOPENID_URL="http://www.api.jsga.gov.cn/api/auth?open_id=openid&app_id=appid&return_url=returnUrl&access_token=sttoken";
	/**
	 * 省厅回跳地址
	 */
	public static String return_url="https://wjw.szgaj.cn/dszgawx/oauth/oauth3";
	/**
	 * 自定义菜单接口(通用接口)
	 */
	public static String CREATEMENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
	public static String GET_URL = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";
	public static String DEL_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";

	/**
	 * 获取用户基本信息(认证服务号的高级接口)
	 */
	public static String WX_USER_INFO="https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID";
	/**
	 * 获取授权用户信息(认证服务号的高级接口)
	 */
	public static String WX_SNSUSER_INFO="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";


	/**
	* 刷新oauth2的access_token接口地址(认证服务号的高级接口)
	*/
	public static String OAUTH_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
	/**
	 * oauth2授权接口,不显示授权页面(认证服务号的高级接口)
	 */
	public static String BASE_URL="https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=http%3A%2F%2F221.224.33.76%2Foswechat%2FoauthServlet%2Foauth.do&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
	/**
	 * oauth2授权接口,显示授权页面(认证服务号的高级接口)
	 */
	public static String USERINFO_URL="https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=http%3A%2F%2F221.224.33.76%2Foswechat%2FoauthServlet%2Foauth.do&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

	/**
	 * 认证用户登陆
	 */
	public static String USERAUTH_URL="api/Users/IsRegUser";

	/**
	 * 获取用户增减数据
	 */
	public static String GETUSERSUMMARY="https://api.weixin.qq.com/datacube/getusersummary?access_token=ACCESS_TOKEN";
	
	/**
	 * 获取累计用户数据
	 */
	public static String GETUSERCUMULATE="https://api.weixin.qq.com/datacube/getusercumulate?access_token=ACCESS_TOKEN";

	/**
	 * 查询统计
	 */
	public static String SEARCHCOUNT_URL="api/SearchCount/SearchCount";


    public static String GETUSERLIST = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID";

    /**
	 * 发起https请求并获取结果
	 *
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式（GET、POST）
	 * @param outputStr
	 *            提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static JSONObject httpsRequest(String requestUrl,
			String requestMethod, String outputStr) {
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
					.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod))// get方式为获取token
				httpUrlConn.connect();

			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.flush();
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (ConnectException ce) {
			ce.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonObject;
	}


	/**
	 * 获取access_token
	 *
	 * @param appid
	 *            凭证
	 * @param appsecret
	 *            密钥
	 * @return
	 */
	public static WxToken getAccessToken(String appid, String appsecret) {
		WxToken wxToken = null;

		String requestUrl = ACCESS_TOKEN_URL.replace("APPID", appid).replace(
				"APPSECRET", appsecret);
		JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
		// 如果请求成功
		if (null != jsonObject) {
			try {
				wxToken = new WxToken();
				wxToken.setAccess_token(jsonObject.getString("access_token"));
				wxToken.setExpires(jsonObject.getInt("expires_in"));
			} catch (Exception e) {
				wxToken = null;
				System.err.println("获取accessToken失败");
				e.printStackTrace();
			}
		}
		return wxToken;
	}

	public static St_AccessToken getST_AccessToken(String appid, String appkey) throws Exception{
		St_AccessToken accessToken = null;

		String requestUrl = ST_ACCESS_TOKEN_URL.replace("STAPPID", appid).replace(
				"STAPPKEY", appkey);
		//JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
		String res=HttpClientUtil.doGet(requestUrl);
		JSONObject jsonObject=JSONObject.fromObject(res);
		// 如果请求成功
		if (null != jsonObject) {
			try {
				accessToken = new St_AccessToken();
				if(jsonObject.getString("ret").equals("1")){
					System.err.println(jsonObject.getString("msg"));
				}
				accessToken.setSt_access_token(jsonObject.getString("data"));
			} catch (Exception e) {
				accessToken = null;
				System.err.println("获取accessToken失败");
				e.printStackTrace();
			}
		}
		return accessToken;
	}

	/***
	 * 获取jsapi_ticket
	 * @param accessToken
	 * @return
     */
	public static String getJsapiTicket(String accessToken){
		String requestUrl = GETTICKET_URL.replace("ACCESS_TOKEN", accessToken);
		JSONObject json = httpsRequest(requestUrl, "GET", null);
		return (String) json.get("ticket");
	}


	/**
	 * 获取微信用户信息
	 * @param accessToken
	 * @param openid
	 * @return
	 */
	public static WX_User getUserInfo(String accessToken,String openid){
		String url=WX_USER_INFO;
		url= url.replace("ACCESS_TOKEN", accessToken).replace("OPENID",openid);
		JSONObject jo=httpsRequest(url,"GET",null);
		if(null!=jo){
			try {
				WX_User user=new WX_User();
				user.setOpenid(jo.getString("openid"));
				user.setSubscribe(jo.getInt("subscribe"));
				user.setSubscribe_time(Long.valueOf(jo.getString("subscribe_time")));
				user.setNickname(filterEmoji(jo.getString("nickname")));
				user.setSex(jo.getInt("sex"));
				user.setCity(jo.getString("city"));
				user.setProvince(jo.getString("province"));
				user.setCountry(jo.getString("country"));
				user.setLanguage(jo.getString("language"));
				user.setHeadimgurl(jo.getString("headimgurl"));
//				user.setUnionid(jo.getString("unionid"));
				System.out.println("获取用户基本信息成功:昵称["+jo.getString("nickname")+"],OPENID["+user.getOpenid()+"]");
				return user;
			} catch (Exception e) {
				WX_User user=new WX_User();
				user.setOpenid(openid);
				user.setSubscribe(0);
//				user.setUnionid(jo.getString("unionid"));
				System.out.println("获取用户基本信息失败:,OPENID["+user.getOpenid()+"]");
				return user;
			}
		}
		return null;
	}

	public static List<WX_User> getUserInfo2(String accessToken,String userO){
		String url="https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=ACCESS_TOKEN";
		url= url.replace("ACCESS_TOKEN", accessToken);
		JSONObject jo=httpsRequest(url,"POST",userO);
		JSONArray jsonArray1=jo.getJSONArray("user_info_list");

		List<WX_User> list=new ArrayList<WX_User>();

		for(int i=0;i<jsonArray1.size();i++){
			WX_User user=new WX_User();
			JSONObject object1=(JSONObject)jsonArray1.get(i);
			user.setOpenid(object1.getString("openid"));
			user.setUnionid(object1.getString("unionid"));
			list.add(user);
		}
		return list;
	}

    /**
     * 获取关注用户的列表List第一位是next_openid
     *
     * @param accessToken
     * @param nextOpenid
     * @return
     */
    public static Object[] getUserList(String accessToken, String nextOpenid) {
        List<Object[]> list = new ArrayList<Object[]>();
        String url = GETUSERLIST;
        url = url.replace("ACCESS_TOKEN", accessToken).replace("NEXT_OPENID", nextOpenid);
        JSONObject jo = httpsRequest(url, "GET", null);
        if (null != jo) {
            try {
                //list 第一位是nextOpenid
                String next_openid = jo.getString("next_openid");
                if("".equals(next_openid)){
                    return null;
                }
                JSONObject json = jo.getJSONObject("data");
                Object[] array = json.getJSONArray("openid").toArray();
                for (int i = 0; i < array.length; i++) {
                    list.add(new Object[]{array[i]});
                }
                return new Object[]{next_openid, list};
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("获取信息失败");
            }
        }
        return null;
    }
	
	public static WX_User getUserInfoMer(String openid,String merid){
		String url=WX_USER_INFO;
		url= url.replace("ACCESS_TOKEN", getAccessTokenMer(merid)).replace("OPENID",openid);
		JSONObject jo=httpsRequest(url,"GET",null);
	//	{"errcode":40001,"errmsg":"invalid credential, access_token is invalid or not latest hint: [13eQSa0821vr22]"}
	//	{"subscribe":0,"openid":"ol7bHt_is9uNAvUrfndvx4-vsI9k","tagid_list":[]}
		if(null!=jo){
			
			if(jo.containsKey("errcode"))
			{
				CacheBaseService.getInstance().delCache("CMCX_ACCESSTOKEN");
				return null;
			}
			
			System.out.println("获取到的微信端用户信息===="+jo.toString());
			WX_User user=new WX_User();
			user.setOpenid(openid);
			user.setSubscribe(jo.getInt("subscribe"));
//			user.setUnionid(jo.getString("unionid"));
			try {
				if(1==user.getSubscribe())
				{
					user.setNickname(filterEmoji(jo.getString("nickname")));
					user.setSex(jo.getInt("sex"));
					user.setCity(jo.getString("city"));
					user.setProvince(jo.getString("province"));
					user.setCountry(jo.getString("country"));
					user.setLanguage(jo.getString("language"));
					user.setHeadimgurl(jo.getString("headimgurl"));
					user.setSubscribe_time(Long.valueOf(jo.getString("subscribe_time")));
					System.out.println("获取用户基本信息成功:昵称["+jo.getString("nickname")+"],OPENID["+user.getOpenid()+"]");
				}
				return user;
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("获取用户基本信息失败:,OPENID["+user.getOpenid()+"]");
				return user;
			}
		}
		return null;
	}
	
	@SuppressWarnings({ "deprecation", "unchecked" })
	public static WX_SNS_User getSNSUserInfo(String accessToken,String openid){
		WX_SNS_User user=new WX_SNS_User();
		String url=WX_SNSUSER_INFO;
		url= url.replace("ACCESS_TOKEN", accessToken).replace("OPENID",openid);
		JSONObject jo=httpsRequest(url,"GET",null);
		if(null!=jo){
			try {
				user.setOpenId(jo.getString("openid"));
				user.setNickname(jo.getString("nickname"));
				user.setSex(jo.getInt("sex"));
				user.setCity(jo.getString("city"));
				user.setProvince(jo.getString("province"));
				user.setCountry(jo.getString("country"));
				user.setHeadimgurl(jo.getString("headimgurl"));
				user.setPrivilegeList(JSONArray.toList(jo.getJSONArray("privilege"),List.class));
				System.out.println("获取用户授权信息成功:昵称["+user.getNickname()+"],OPENID["+user.getOpenId()+"]");
				return user;
			} catch (Exception e) {
				System.err.println("获取用户信息失败");
			}
		}
		return null;
	}

	public static WXOauth2Token getOauth2AccessToken(String appId,String appSecret,String code){
		String requestUrl=OAUTH_ACCESS_TOKEN_URL;
		requestUrl=requestUrl.replace("APPID", appId).replace("SECRET", appSecret).replace("CODE", code);
		JSONObject jo=httpsRequest(requestUrl,"GET",null);
		System.out.println("---getOauth2AccessToken-----"+appId+"====appId===="+appSecret+"===appSecret===="+code+"===code====");
		try {
			if(null!=jo){
				WXOauth2Token wat=new WXOauth2Token();
				System.out.println("=====获取access_token：###"+jo.toString());
				wat.setAccessToken(jo.getString("access_token"));
				System.out.println("access_token"+jo.getString("access_token"));
				wat.setExpiresIn(jo.getInt("expires_in"));
				wat.setRefreshToken(jo.getString("refresh_token"));
				wat.setOpenId(jo.getString("openid"));
				wat.setScope(jo.getString("scope"));
				return wat;
			}else {
				System.out.println("======jo=NUll===="+jo);
			}
		} catch (Exception e) {
			System.out.println("=====getOauth2AccessToken：###报错");
			e.printStackTrace();
		}
		return new WXOauth2Token();
	}

	/**
	 * 刷新access_token
	 * @param appId
	 * @param refreshToken
	 * @return
	 */
	public static WXOauth2Token refreshOauth2AccessToken(String appId,String refreshToken){
		WXOauth2Token wat=new WXOauth2Token();
		String requestUrl="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
		requestUrl=requestUrl.replace("APPID", appId).replace("REFRESH_TOKEN", refreshToken);
		JSONObject jo=httpsRequest(requestUrl, "GET", null);
		if(null!=jo){
			wat.setAccessToken(jo.getString("access_token"));
			wat.setExpiresIn(jo.getInt("expires_in"));
			wat.setRefreshToken(jo.getString("refresh_token"));
			wat.setOpenId(jo.getString("openid"));
			wat.setScope(jo.getString("scope"));
		}
		return wat;
	}
	
	/***
	 * 
	 * @param type 0 用户增加  1用户累计
	 * @param access_token
	 * @param start
	 * @param end
	 * @return
	 */
	public static String getUserCountInfo(String type, String access_token,String start,String end) {
		String requestUrl = GETUSERSUMMARY;
		if("1".equals(type))		
		{
			requestUrl = GETUSERCUMULATE;
		}
		requestUrl = requestUrl.replace("ACCESS_TOKEN", access_token);	
		com.alibaba.fastjson.JSONObject param = new com.alibaba.fastjson.JSONObject();
		param.put("begin_date", start);
		param.put("end_date", end);
		
		String result = null;
		try {
			result = HttpClientUtil.post(requestUrl, param);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	
	public static String getOpenId(HttpServletRequest request)
	{
		String code = request.getParameter("code");
		String merid = (String) request.getSession().getAttribute("merid");
		if(!StringUtils.hasText(code)||!StringUtils.hasText(merid))
		{
			System.out.println("-------拿不到code和merid返回空");
			return "";
		}

		WxToken token = loadTokenByMerid(merid);
		WXOauth2Token o = WeixinUtil.getOauth2AccessToken(token.getAppid(), token.getAppsecret(), code);
		String openId = o.getOpenId();
		return openId;
	}

	/**
	 * 从省厅获取权限
	 * @return
     */
	public static String getSTOpenId(String openid,String appid,String accessToken) throws  Exception{
		String requestUrl=ST_GET_STOPENID_URL;
		requestUrl=requestUrl.replace("openid", openid).replace("appid", appid).replace("returnUrl", WeixinUtil.return_url).replace("sttoken",accessToken);
		//JSONObject jo=httpsRequest(requestUrl,"GET",null);
		//String res=HttpClientUtil.doGet(requestUrl);

		return requestUrl;
	}
	public static boolean checkIsLoginUser(HttpServletRequest request) throws IllegalArgumentException, IOException {
		//从session中拿到openId
		HttpSession session = request.getSession();
		Member member =(Member)session.getAttribute(Constant.SESSION_USER);
		if(null!=member){
			return true;
		}else{
			String openId=(String)session.getAttribute("openId");//
			if(StringUtils.isEmpty(openId))
			{
				return false;
			}
			com.alibaba.fastjson.JSONObject json= com.alibaba.fastjson.JSONObject.parseObject("{ \"OpenId\":\"" + openId + "\",  \"UserSource\":3}");
			System.out.println("======参数"+json.toString());
			System.out.println("======url"+Constant.host5+USERAUTH_URL);
			String a= HttpClientUtil.post(Constant.host5+USERAUTH_URL, json);
			System.out.println("======checkIsLoginUser"+a);
			com.alibaba.fastjson.JSONObject jsona= com.alibaba.fastjson.JSONObject.parseObject(a);
			//String openId = (String)sessiion.getAttribute("openId");
			/**
			 *如果是绑定用户，存session，把用户信息放到session里
			 */
			if((Boolean)jsona.get("succ")){
				if(null==member){
					try {
						member =SetMember(com.alibaba.fastjson.JSONObject.parseObject(jsona.get("data").toString()));
					}catch(Exception e){
						e.printStackTrace();
					}
					member.setOpenId(openId);
					session.setAttribute(Constant.SESSION_USER,member);
				}
			}
			return (Boolean)jsona.get("succ");
		}

	}
	public static<T> Object JSONToObj(String jsonStr,Class<T> obj) {
		T t = null;
		try {
			ObjectMapper objectMapper = new ObjectMapper();
			t = objectMapper.readValue(jsonStr,
					obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return t;
	}
	public static Member SetMember(com.alibaba.fastjson.JSONObject jsonarry) throws Exception{
		Member member = new Member();
		String s = jsonarry.get("ADDRESS").toString();
		member.setAddress(s);
//		member.setBirthday(new Date());
		member.setContacts(jsonarry.get("LINKNAME").toString());
//		member.setCorporate(json.get("Guid").toString());
//		member.setDrivingLic(json.get("Guid").toString());
		member.setEmail(jsonarry.get("EMAIL").toString());
//		member.setFileId(json.get("Guid").toString());
//		member.setGender(0);
		member.setGuid(jsonarry.get("GUID").toString());
//		member.setOpenId(jsonarry.get("OPENID").toString());
//		member.setId(2);
		DesUtil tools = new DesUtil();
		try{
		if("0".equals(jsonarry.get("USERTYPE").toString())){
			member.setOrgId(tools.decode(jsonarry.get("USERCODE").toString()));
		}else{
			member.setIdCard(tools.decode(jsonarry.get("USERCODE").toString()));
		}}catch (Exception e){
			if("0".equals(jsonarry.get("USERTYPE").toString())){
				member.setOrgId(jsonarry.get("USERCODE").toString());
			}else{
				member.setIdCard(jsonarry.get("USERCODE").toString());
			}
		}

		member.setLoginId(jsonarry.get("USERNAME").toString());
//		member.setLoginTime(new Date());
//		member.setLpn(json.get("Guid").toString());
		try{
		member.setMobile(tools.decode(jsonarry.get("MOBILE").toString()));}
		catch (Exception e){
			member.setMobile(jsonarry.get("MOBILE").toString());
		}
//		member.setOauthToken(json.get("Guid").toString());
//		member.setOpenId(json.get("Guid").toString());
//		member.setOrgId(json.get("Guid").toString());
//		member.setPassport(json.get("Guid").toString());
//		member.setPassword(json.get("Guid").toString());
		member.setRealName(jsonarry.get("ALIASNAME").toString());
//		member.setRegTime(new Date());
//		member.setSort(1);
//		member.setStatus(1);
		member.setTel(jsonarry.get("TELEPHONE").toString());
//		member.setType(1);
//		member.setUidTw(json.get("Guid").toString());
		member.setUnit(Integer.parseInt(jsonarry.get("USERTYPE").toString()));
		try{
		member.setUnionid(jsonarry.get("temp11").toString());
		}catch(Exception e){

		}
//		member.setUserSrc(1);
//		member.setValidateCode(json.get("Guid").toString());
//		member.setVin(json.get("Guid").toString());
		return member;
	}


	/**
	 *过滤EMOJI表情
	 */
	public static String filterEmoji(String source) {
		if(source != null)
		{
			Pattern emoji = Pattern.compile ("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",Pattern.UNICODE_CASE | Pattern . CASE_INSENSITIVE ) ;
			Matcher emojiMatcher = emoji.matcher(source);
			if ( emojiMatcher.find())
			{
				source = emojiMatcher.replaceAll("*");
				return source ;
			}
			return source;
		}
		return source;
	}
	/***
	 * 查询统计接口
	 * @param searchtype 1办件查询 2身份证进度查询 3居住证办理进度查询 5居住证办理点查询 4案件查询 6货车临时通行证查询 7邮政专用查询 8在押人员消费查询 9其他
	 * @param searchname 查询名称
	 * @return
	 */
	public static Result gesearchCountInfo(String searchtype, String searchname) {
		/*String requestUrl = Constant.host5+SEARCHCOUNT_URL;
		Map<String, String> param = new HashMap<String, String>();
		param.put("SEARCHTYPE", searchtype);
		param.put("SEARCHNAME", searchname);
		param.put("SEARCHMEANS", "3");
		Result result = com.alibaba.fastjson.JSONObject.parseObject(HttpClientUtil.doPost(requestUrl, param,"utf-8"), Result.class);
		return result;*/
		return null;
	}

	/**
	 * 根据公众平台商家openid获取公众号配置信息
	 * @return
	 */
	public static WxToken loadTokenByOpenid(String wx_openid) {
		return (WxToken)CommonUtilCache.getItem("wxTokenOpenidMap:" + wx_openid);
	}

	/**
	 * 根据公众平台商家Id获取公众号配置信息
	 * @return
	 */
	public static WxToken loadTokenByMerid(String sid) {
		return (WxToken)CommonUtilCache.getItem("wxTokenMap:" + sid);
	}


	/**
	 * 根据公众平台商家openid查询更新access_token
	 * @return
	 */
	public static String getAccessToken(String wx_openid) {
		String access_token = "";
		String cachekey = "ACCESSTOKEN:"+wx_openid;
		if("gh_b6af115f3e1a".equals(wx_openid)){
			return access_token;
		}else {
			if (CacheBaseService.getInstance().exists(cachekey)) {
				access_token = CacheBaseService.getInstance().get(cachekey);
			} else {
				WxToken token = loadTokenByOpenid(wx_openid);
				WxToken at = WeixinUtil.getAccessToken(token.getAppid(), token.getAppsecret());
				access_token = at.getAccess_token();
				CacheBaseService.getInstance().cache(cachekey, access_token, 7200l);
			}
			if ("".equals(access_token) || null == access_token) {
				WxToken token = loadTokenByOpenid(wx_openid);
				WxToken at = WeixinUtil.getAccessToken(token.getAppid(), token.getAppsecret());
				access_token = at.getAccess_token();
				CacheBaseService.getInstance().cache(cachekey, access_token, 7200l);
			}

			return access_token;
		}
	}

	/**
	 * 根据公众平台商家Id查询更新access_token
	 * @return
	 */
	public static String getAccessTokenMer(String merchant_id) {
		WxToken token = loadTokenByMerid(merchant_id);
		return getAccessToken(token.getOpenid());
	}
}
